/*
 ============================================================================
 Name        : aatracker.c
 Author      : Andre
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/time.h>
#include <time.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>

#include "aatracker.h"
#include "requesthandler.h"
#include "urlhandler.h"
#include "bencoder.h"
#include "datastore.h"
#include "networkhandler.h"
#include "trackerutils.h"
#include "trackerlogger.h"


int handleRequest(int sock){

    char requestStr[MAX_CHARS_IN_REQUEST];


    int receivedChars = recv(sock, requestStr,MAX_CHARS_IN_REQUEST, 0);

    printf("received %d chars:\n", receivedChars);
    printf("received string: %s\n", requestStr);

    sendHttpOKStatus(sock);

    if (isAnnounce(requestStr)){

        AnnounceParameters ap;
        BencodedResponse br;

        int numIdentifiedParameters= getAnnounceParameters(requestStr, &ap);

        if (numIdentifiedParameters < MINIMAL_NUMBER_OF_PARAMETERS){

            logStackTrace("handleRequest", __FILE__, __LINE__);
            bencodeErrorMessage("erro obtendo parametros do request", &br);
            sendTrackerBencodedResponse(sock, &br);
            return ERROR_GETTING_ANNOUNCE_PARAMETERS;
        }

        int  reqStatus = doAnnounce(ap, &br);

        if (numIdentifiedParameters != OK){

            logStackTrace("handleRequest", __FILE__, __LINE__);
            bencodeErrorMessage("erro obtendo announce response do tracker", &br);
            sendTrackerBencodedResponse(sock, &br);
            return ERROR_GETTING_ANNOUNCE_RESPONSE;
        }

       sendTrackerBencodedResponse(sock, &br);

    }else if(isScrape(requestStr)) {

        //doScrape(ap, br);
        //sendTrackerBencodedResponse(sock, &br);

    }

    //se chegar aqui, eh pq nao identificou o request
    BencodedResponse br;
    logError("requestHandler()", "request is of unknown type", __FILE__, __LINE__, 0);
    bencodeErrorMessage("request is of unknown type", &br);
    sendTrackerBencodedResponse(sock, &br);
    return FAILED_TO_IDENTIFY_REQUEST_TYPE;
}


int doAnnounce(AnnounceParameters ap, BencodedResponse *br){

    AnnounceResults ar;

    getPeerDataFromStorage(&ap, &ar);

    if (ap.event == STARTED) {
        addPeerDataToStorage(&ap);

    }else if (ap.event == STOPPED) {
        removePeerDataFromStorage(&ap);
    }

    bencodeAnnounceResponse(&ar, br);

    return OK;
}

/*int doScrape(TrackerScrape ts, BencodedResponse br){

    ScrapeResponse sr;

    bencodeScrapeResponse(&sr, &br);

    return OK;
}
*/
